<?php

namespace App\Service\WorkOrder\Web;

use App\Enums\Check\CheckEnum;
use App\Enums\WorkOrder\ErrCode;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Models\Common\ResourcesModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerSubmitHistoryModel;
use App\Models\WorkOrder\WorkOrderProductCompanyModel;
use App\Models\WorkOrder\WorkOrderRejectModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Service\WorkOrder\ProblemFeedbackService;
use App\Service\WorkOrder\WorkOrderBaseService;
use App\Support\CustomForm\AttributeWorkOrderSupport;
use App\Support\CustomForm\ValidateSupport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProblemFeedbackWebService
{
    public static function baseWorkOrderInfo(string $workOrderNo): array
    {
        //通过工单号获取问题类型
        $problemInfo = WorkOrderApplyMainModel::query()
                                              ->where('workOrderNo', $workOrderNo)
                                              ->first();
        $contentInfo = WorkOrderApplyContentModel::query()
                                                 ->where('workOrderNo', $workOrderNo)
                                                 ->select('id', 'content')
                                                 ->first();

        if (null === $problemInfo || null === $contentInfo) {
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_WORK_ORDER_NO));
        }

        //基本数据
        $argument = json_decode($contentInfo['content'], true);
        //文件资源字段
        $fileKey = [];
        //处理人表单
        $handleForm = [];
        //生产厂家表单
        $factoryForm = [];
        switch ($problemInfo['problemPid']) {
            case 0:
                break;
            case OrderEnum::PROBLEM_PID_1:
                $fileKey = OrderEnum::PROBLEM_PID_1_CHILDREN_FILE[$problemInfo['problemChildId']] ?? [];
                break;
            case OrderEnum::PROBLEM_PID_2:
                $fileKey     = OrderEnum::PROBLEM_PID_2_CHILDREN_FILE[$problemInfo['problemChildId']] ?? [];
                $factoryForm = self::getFactoryByGoods($contentInfo);
                break;
            case OrderEnum::PROBLEM_PID_4:
                $fileKey = OrderEnum::PROBLEM_PID_4_CHILDREN_FILE[$problemInfo['problemChildId']] ?? [];

                // 展柜和炸炉工单 增加 设备名称、设备供应商、设备下单时间、设备发货时间  字段
                if (in_array($problemInfo['problemChildId'], [OrderEnum::PROBLEM_PID_4_CHILDREN_1, OrderEnum::PROBLEM_PID_4_CHILDREN_2, OrderEnum::PROBLEM_PID_4_CHILDREN_13])) {
                    $factoryForm = self::getDeviceNameAndFactory($problemInfo, $contentInfo);
                }
                break;
            case OrderEnum::PROBLEM_PID_6:
            case OrderEnum::PROBLEM_PID_7:
            case OrderEnum::PROBLEM_PID_8:
            case OrderEnum::PROBLEM_PID_9:
            case OrderEnum::PROBLEM_PID_10:
                $fileKey = OrderEnum::PROBLEM_PID_6_10_CHILDREN_FILE;
                break;
        }

        $handleForm = self::getHandleInfo($problemInfo, OrderEnum::PROBLEM_PID_TO_ROLE[$problemInfo->problemPid] ?? 0,
            $problemInfo->problemPid, $problemInfo->problemChildId);

        //文件数据
        $resources = (array)ResourcesModel::getModuleBusinessResources(
            ResourcesModel::MODULE_TYPE_WORK_ORDER,
            ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK,
            $contentInfo['id'],
            $fileKey
        );

//        $arguments = array_merge($argument, $resources);
        $arguments = array_merge($argument, collect($resources)->map(function($val, $key)use($argument){
            if(isset($argument[$key]) && !empty($argument[$key]) && empty($val)){
                $val = $argument[$key];
            }
            return $val;
        })->toArray());

        return [$problemInfo, $contentInfo, $arguments, $handleForm, $factoryForm];
    }

    public static function getWorkOrderInfo($workOrderNo)
    {
        list($problemInfo, $contentInfo, $arguments, $handleForm, $factoryForm) = self::baseWorkOrderInfo($workOrderNo);

        //基础表单信息
        $baseInfo = ProblemFeedbackService::getProblemForm($problemInfo['problemPid'], $problemInfo['problemChildId'],
            $problemInfo['shopId'], $arguments, OrderEnum::PROBLEM_FEEDBACK_INFO_USE_WEB);

        foreach ($baseInfo['form'] as $k => $item) {
            if (in_array($item['field'], OrderEnum::FORM_SPECIAL_ITEM)) {
                unset($baseInfo['form'][$k]);
            }
        }

        if (!empty($handleForm)) {
            $baseInfo['form'] = array_merge($baseInfo['form'], [$handleForm]);
        }

        if (!empty($factoryForm)) {
            if (
                $problemInfo['problemPid'] == OrderEnum::PROBLEM_PID_4 &&
                in_array($problemInfo['problemChildId'], [OrderEnum::PROBLEM_PID_4_CHILDREN_1, OrderEnum::PROBLEM_PID_4_CHILDREN_2, OrderEnum::PROBLEM_PID_4_CHILDREN_13])
            ) {
                $baseInfo['form'] = array_merge($baseInfo['form'], $factoryForm);
            } else {
                $baseInfo['form'] = array_merge($baseInfo['form'], [$factoryForm]);
            }
        }
        return [
            'id'          => $contentInfo->id,
            'formDesc'    => $baseInfo['title'],
            'formContent' => [
                [
                    'title'      => '工单信息', //默认
                    'attributes' => array_values($baseInfo['form']),
                ]
            ]
        ];
    }


    /**
     * 获取处理人列表及其处理人
     * @param $workOrderNo
     * @param $role
     * @return array
     */
    public static function getHandleInfo($workOrderModel, $role, int $problemPid, int $problemChildId): array
    {
        if (in_array($workOrderModel->problemPid, OrderEnum::PROBLEM_NOT_NEED_HANDLE)) {
            return [];
        }
        $managerList = WorkOrderUserRoleModel::query()
                                             ->getUsersByRole($role, $problemPid, $problemChildId);
        //获取处理人
        $handle = WorkOrderApplyManagerModel::query()
                                            ->where('workOrderNo', $workOrderModel->workOrderNo)
                                            ->where('role', $role)
                                            ->where('managerId', '>', 0)
                                            ->pluck('managerId')
                                            ->toArray();

        $nextForm = WorkOrderBaseService::singleFormBuild(
            'handle',
            AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE,
            WorkOrderUserRoleModel::ROLE_TYPE_TEXT[$role] ?? '处理人'
        )
                                        ->setCustomAttribute(['icon', 'arrow-right'])
                                        ->setValidateRules(ValidateSupport::getInstance(true))
                                        ->setCustomAttribute(['options', $managerList])
                                        ->setValue(function () use ($handle) {
                                            return empty($handle) ? null : $handle;
                                        });
        if (!empty($handle)) {
            $nextForm->setCustomAttribute(['disabled', true]);
        }
        return $nextForm->build();
    }

    /**
     * 根据商品名称显示生产厂家  名字模糊
     * @param $applyMainModel
     * @return array
     */
    public static function getFactoryByGoods($applyMainModel): array
    {
        //获取已选择商品
        $content = json_decode($applyMainModel->content, true);
        if (!isset($content['errJdeCodes'])) {
            return [];
        }
        $chooseFactory = $content['chooseFactory'] ?? null;
        $required      = false;
        $tempFactory   = [];
        foreach ($content['errJdeCodes'] as $errGoods) {
            $tempFactory[($errGoods['supplier_id'] ?? 0)] = [
                'text'  => $errGoods['supplier_name'] ?? '其他',
                'value' => $errGoods['supplier_id'] ?? 0,
            ];
        }

        if (!$chooseFactory) {
            //不存在
            $required = true;
            if ($tempFactory) {
                $factory       = array_values($tempFactory);
                $chooseFactory = collect($factory)->pluck('value')->toArray();
            }
        }
        $factory   = ProblemFeedbackService::getOrmSupplier();//查询所有厂家信息
        $factory[] = [
            'text'  => '其他',
            'value' => 0
        ];
        //组件form表单
        $nextForm = WorkOrderBaseService::singleFormBuild(
            'chooseFactory',
            AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE,
            '生产厂家'
        )
                                        ->setCustomAttribute(['icon', 'arrow-right'])
                                        ->setValidateRules(ValidateSupport::getInstance($required))
                                        ->setCustomAttribute(['options', $factory])
                                        ->setValue($chooseFactory);

        return $nextForm->build();
    }

    /**
     * 获取备注  默认客服
     * @param $workOrderNo
     * @param int $role
     * @return string
     */
    public static function getRemarkToService($workOrderNo, int $role = WorkOrderUserRoleModel::ROLE_TYPE_1): string
    {
        return (string)WorkOrderApplyManagerModel::query()->where('workOrderNo', $workOrderNo)->where('role', $role)
                                                 ->value('remark');
    }

    /**
     * 获取所有负责人映射
     * @param WorkOrderApplyMainModel $applyMainModel
     * @return array
     */
    public static function handleProcedureInfo(WorkOrderApplyMainModel $applyMainModel): array
    {
        // 所有驳回中的userIds
        $rejectUids = WorkOrderRejectModel::query()
                                          ->where('workOrderNo', $applyMainModel->workOrderNo)
                                          ->where('status', WorkOrderRejectModel::STATUS_INIT)
                                          ->pluck('createdByUid')
                                          ->toArray();

        $list = WorkOrderApplyManagerModel::query()
                                          ->where('workOrderNo', $applyMainModel->workOrderNo)
                                          ->with(["remarkRel", "solutionRel"])
                                          ->select([
                                              'id',
                                              'managerId',
                                              'managerName',
                                              'remark',
                                              'solution',
                                              'role',
                                              'status',
                                              'submitTime'
                                          ])
                                          ->get()
                                          ->map(function (WorkOrderApplyManagerModel $v) use (
                                              $applyMainModel,
                                              $rejectUids
                                          ) {
                                              if ($v->status == MissionEnum::MISSION_STATUS_0 && $v->managerId == FeishuWebAuth::$userId && $applyMainModel->status == OrderEnum::MAIN_STATUS_ING) {
                                                  $v->hasAuth = true;
                                              } else {
                                                  $v->hasAuth = false;
                                              }
                                              $v->showClose = $v->submitTime > 0 ? 0 : OrderListService::showClose(
                                                  $applyMainModel,
                                                  $v->managerId
                                              );


                                              if ($v->submitTime > 0 || $applyMainModel->sourceType != WorkOrderApplyMainModel::SOURCE_TYPE_0) {
                                                  $v->showReject = 0;
                                              } else {
                                                  if (in_array($v->managerId, $rejectUids)) {
                                                      $v->showReject = 0;
                                                  } else {
                                                      $v->showReject = 1;
                                                  }
                                              }


                                              if ($applyMainModel->problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105 && $applyMainModel->step == MissionEnum::STEP_7 && $v->managerId == FeishuWebAuth::$userId) {//夸父收银进件2.0 富友审核中都可以提交和驳回
                                                  $v->hasAuth    = true;
                                                  $v->showReject = 1;
                                              }

                                              $v->remarkHistory = $v->remarkRel->map(function (
                                                  WorkOrderApplyManagerSubmitHistoryModel $applyManagerSubmitHistoryModel
                                              ) {
                                                  return [
                                                      "id"              => $applyManagerSubmitHistoryModel->id,
                                                      "type"            => $applyManagerSubmitHistoryModel->type,
                                                      "content"         => $applyManagerSubmitHistoryModel->content,
                                                      "createdUsername" => $applyManagerSubmitHistoryModel->createdUsername,
                                                      "createdAt"       => $applyManagerSubmitHistoryModel->createdAt->format("Y-m-d H:i:s"),
                                                      "submitTime"      => $applyManagerSubmitHistoryModel->submitTime
                                                  ];
                                              });

                                              $v->offsetUnset("remarkRel");

                                              $v->solutionHistory = $v->solutionRel->map(function (
                                                  WorkOrderApplyManagerSubmitHistoryModel $applyManagerSubmitHistoryModel
                                              ) {
                                                  return [
                                                      "id"              => $applyManagerSubmitHistoryModel->id,
                                                      "type"            => $applyManagerSubmitHistoryModel->type,
                                                      "content"         => $applyManagerSubmitHistoryModel->content,
                                                      "createdUsername" => $applyManagerSubmitHistoryModel->createdUsername,
                                                      "createdAt"       => $applyManagerSubmitHistoryModel->createdAt->format("Y-m-d H:i:s"),
                                                  ];
                                              });

                                              $v->offsetUnset("solutionRel");

                                              return $v;
                                          });


        return [
            'userId'          => FeishuWebAuth::$userId,
            'customerService' => array_values($list->where('role', WorkOrderUserRoleModel::ROLE_TYPE_1)->toArray()),
            'handle'          => array_values($list->where('role', '>', WorkOrderUserRoleModel::ROLE_TYPE_1)->toArray())
        ];
    }

    /**
     * 修改工单
     * @param string $workOrderNo
     * @param $params
     * @param $userId
     * @param int $problemPid
     * @return array
     */
    public static function renewByProblemFeedback(string $workOrderNo, $params, $userId, int $problemPid)
    {
        $applyMain = WorkOrderApplyMainModel::getDetailByWorkOrderNo($workOrderNo);

        if ($applyMain->step >= MissionEnum::STEP_99) {//工单任务完成前，都可以编辑工单的信息
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_STEP_NORMAL_OFF));
        }
        //数据平铺
        $params['problemPid'] = $problemPid;
        //添加审批人记录
        $handle      = $params['handle'] ?? [];
        $handleArr   = [];
        $userNameArr = WorkOrderUserRoleModel::query()->whereIn('userId', $handle)->pluck('name', 'userId')->toArray();

        //获得已经拥有的处理记录
        $userIds = WorkOrderApplyManagerModel::query()
                                             ->where('workOrderNo', $workOrderNo)
                                             ->where('role', '>', WorkOrderUserRoleModel::ROLE_TYPE_1)
                                             ->where('status', WorkOrderApplyManagerModel::STATUS_ON)
                                             ->pluck('managerId')
                                             ->toArray();

        foreach ($handle as $item) {
            if (in_array($item, $userIds)) {
                continue;
            }
            $handleArr[] = [
                'workOrderNo'  => $workOrderNo,
                'role'         => OrderEnum::PROBLEM_PID_TO_ROLE[$problemPid] ?? 0,
                'managerId'    => $item,
                'managerName'  => $userNameArr[$item] ?? '',
                'remark'       => '',
                'solution'     => '',
                'createdByUid' => $userId,
                'updatedByUid' => $userId,
                'createdAt'    => time(),
                'updatedAt'    => time(),
            ];
        }
        //获取资源文件
        $fileArr = [];
        switch ($applyMain->problemPid) {
            case 0:
                break;
            case OrderEnum::PROBLEM_PID_1:
                $fileArr = OrderEnum::PROBLEM_PID_1_CHILDREN_FILE[$applyMain->problemChildId] ?? [];

                break;
            case OrderEnum::PROBLEM_PID_2:
                $fileArr = OrderEnum::PROBLEM_PID_2_CHILDREN_FILE[$applyMain->problemChildId] ?? [];
                break;
            case OrderEnum::PROBLEM_PID_4:
                $fileArr = OrderEnum::PROBLEM_PID_4_CHILDREN_FILE[$applyMain->problemChildId] ?? [];
                break;
            case OrderEnum::PROBLEM_PID_6:
            case OrderEnum::PROBLEM_PID_7:
            case OrderEnum::PROBLEM_PID_8:
            case OrderEnum::PROBLEM_PID_9:
            case OrderEnum::PROBLEM_PID_10:
                $fileArr = OrderEnum::PROBLEM_PID_6_10_CHILDREN_FILE ?? [];
                break;
        }
        $resources = [];
        foreach ($fileArr as $value) {
            if (!isset($params[$value])) {
                continue;
            }
            $resources[$value] = $params[$value];
            unset($params[$value]);
        }

        DB::beginTransaction();
        try {
            //添加审批记录
            WorkOrderApplyManagerModel::query()->insert($handleArr);
            if (!empty($resources)) {
                $businessId = (int)WorkOrderApplyContentModel::query()->where('workOrderNo', $workOrderNo)->value('id');
                $data       = [];
                //先删除所有文件  后添加
                ResourcesModel::query()
                              ->where('businessId', $businessId)
                              ->where('module', ResourcesModel::MODULE_TYPE_WORK_ORDER)
                              ->where('business', ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK)
                              ->update([
                                  'isDeleted' => 1
                              ]);
                foreach ($resources as $key => $resource) {
                    foreach ($resource as $item) {
                        $data[] = [
                            'businessId'   => $businessId,
                            'module'       => ResourcesModel::MODULE_TYPE_WORK_ORDER,
                            'business'     => ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK,
                            'name'         => $key,
                            'url'          => getPrivateFileKey($item),
                            'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                            'createdAt'    => time(),
                            'updatedAt'    => time(),
                            'createdByUid' => $userId,
                            'updatedByUid' => $userId,
                        ];
                    }
                }
                ResourcesModel::query()->insert($data);
            }
            //主表修改
            if (isset($params['problemDesc'])) {
                WorkOrderApplyMainModel::query()
                                       ->where('workOrderNo', $workOrderNo)
                                       ->update([
                                           "problemChildId" => $params["problemChildId"],
                                           'problemDesc'    => $params['problemDesc']
                                       ]);
            }
            $params['bookNo'] = (array)($params['bookNo'] ?? []);
            //详情表修改
            WorkOrderApplyContentModel::query()
                                      ->where('workOrderNo', $workOrderNo)
                                      ->update([
                                          'content' => json_encode($params, JSON_UNESCAPED_UNICODE)
                                      ]);
            DB::commit();
            return [];
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info('修改工单失败' . $exception->getMessage());
            throw new CustomHttpResponseException(ErrCode::errCodeTrans(ErrCode::CODE_ERR_UPDATE_WORK_ORDER));
        }

    }


    /**
     * 展柜和炸炉工单 增加 设备名称、设备供应商、设备下单时间、设备发货时间  字段
     * @param $applyMainModel
     * @param $contentInfo
     * @return array
     */
    public static function getDeviceNameAndFactory($applyMainModel, $contentInfo): array
    {
        switch ($applyMainModel['problemChildId']) {
            case OrderEnum::PROBLEM_PID_4_CHILDREN_1:
                $goodsNames = '炸炉';
                break;
            case OrderEnum::PROBLEM_PID_4_CHILDREN_2:
                $goodsNames = '展示柜';
                break;
            case OrderEnum::PROBLEM_PID_4_CHILDREN_13:
                $goodsNames = '净水器';
                break;
            default:
                $goodsNames = '';
        }
        if (!$goodsNames) {
            return [];
        }

        // 订货订单列表
        $list = self::getEquipmentDeliveryList($applyMainModel['shopId'], $goodsNames);

        // 表单内容
        $content = json_decode($contentInfo->content, true);

        $deviceName         = $content['deviceName'] ?? null;        //设备名称
        $chooseFactory      = $content['chooseFactory'] ?? null;     //设备供应商-厂家
        $deviceCreateTime   = $content['deviceCreateTime'] ?? null;  //设备下单时间-支付时间
        $deviceDeliveryTime = $content['deviceDeliveryTime'] ?? null;//设备发货时间-直配出库单 创建时间

        $required    = false;
        $tempFactory = [];
        if (!empty($list)) {
            if (!$deviceName) {
                $deviceName = $list['goodsNames'] ?? "";
            }
            if (!$deviceCreateTime) {
                $deviceCreateTime = $list['paidAt'] ? date('Y-m-d', strtotime($list['paidAt'])) : null;
            }
            if (!$deviceDeliveryTime) {
                $deviceDeliveryTime = $list['createdAt'] ? date('Y-m-d', strtotime($list['createdAt'])) : null;
            }

            $tempFactory[$list['supplierId'] ?? 0] = [
                'text'  => $list['supplierName'] ?? '其他',
                'value' => $list['supplierId'] ?? 0,
            ];
        }
        if (!$deviceName) {
            $deviceName = $goodsNames;//如果没有订货订单关联信息，名称默认为「炸炉」或「展柜」
        }


        if (!$chooseFactory) {
            //不存在
            $required = true;
            if ($tempFactory) {
                $factory       = array_values($tempFactory);
                $chooseFactory = collect($factory)->pluck('value')->toArray();
            }
        }
        $factory   = ProblemFeedbackService::getOrmSupplier();//查询所有厂家信息
        $factory[] = [
            'text'  => '其他',
            'value' => 0
        ];

        // 组件form表单
        $nextForm   = [];
        $nextForm[] = WorkOrderBaseService::singleFormBuild(
            'deviceName',
            AttributeWorkOrderSupport::INPUT_TYPE_TEXT,
            '设备名称'
        )
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setValue($deviceName)->build();

        $nextForm[] = WorkOrderBaseService::singleFormBuild(
            'chooseFactory',
            AttributeWorkOrderSupport::INPUT_TYPE_SELECT_MULTIPLE,
            '设备供应商'
        )
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setValidateRules(ValidateSupport::getInstance($required))
            ->setCustomAttribute(['options', $factory])
            ->setValue($chooseFactory)->build();

        $nextForm[] = WorkOrderBaseService::singleFormBuild(
            'deviceCreateTime',
            AttributeWorkOrderSupport::INPUT_DATE,
            '设备下单时间'
        )
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setCustomAttribute(['format', 'YYYY-MM-DD'])
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setValue($deviceCreateTime)->build();


        $nextForm[] = WorkOrderBaseService::singleFormBuild(
            'deviceDeliveryTime',
            AttributeWorkOrderSupport::INPUT_DATE,
            '设备发货时间'
        )
            ->setCustomAttribute(['icon', 'arrow-right'])
            ->setCustomAttribute(['format', 'YYYY-MM-DD'])
            ->setValidateRules(ValidateSupport::getInstance(true))
            ->setValue($deviceDeliveryTime)->build();

        return $nextForm;
    }

    /**
     * 获取订货单匹配对应设备名称
     * @param $shopId
     * @param $goodsNames
     * @return array
     */
    public static function getEquipmentDeliveryList($shopId, $goodsNames): array
    {
        $body = OrmNewOrderRemote::equipmentDeliveryNotes($shopId, '2099-12-31', CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT);

        $orders = collect($body['data']['orders'] ?? [])->keyBy('id');

        // 订货订单列表
        $list = [];
        collect($body['data']['list'] ?? [])
            ->map(
                function ($item) use (&$list, $orders, $goodsNames) {
                    if (!$list) {
                        $data = [
                            'id'               => $item['deliveryNoteId'],
                            'orderCode'        => $item['orderCode'],
                            'deliveryNoteCode' => $item['deliveryNoteCode'],
                            'statusText'       => $item['statusText'],
                            'payStatusText'    => $item['paymentStatusText'],
                            'createdAt'        => $item['create_time'],
                            'paidAt'           => $orders[$item['newOrderId']]['paidAt'] ?? "",
                            'status'           => $item['status'],
                            'orderStatus'      => $item['orderStatus'],
                            'goodsNames'       => $item['goodsNames'],
                            'supplierName'     => $item['supplierName'],
                            'supplierId'       => $item['supplierId'] ?? 0,
                        ];
                        if (count($item['goodsNames']) > 1) {
                            foreach ($item['goodsNames'] as $goodsName) {
                                if (mb_strpos($goodsName, $goodsNames) !== false) {
                                    $data['goodsNames'] = $goodsName;
                                    $list               = $data;
                                }
                            }
                        } elseif (count($item['goodsNames']) == 1) {
                            if (mb_strpos($item['goodsNames'][0], $goodsNames) !== false) {
                                $data['goodsNames'] = $item['goodsNames'][0];
                                $list               = $data;
                            }
                        }
                    }
                }
            );
        return $list;
    }
}
